﻿Imports TBCC.UserManage
Public Class ProjectOutlineForm

    Sub New()

        ' 此调用是 Windows 窗体设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。
        SetStyle(ControlStyles.AllPaintingInWmPaint, True)
        SetStyle(ControlStyles.UserPaint, True)
        SetStyle(ControlStyles.OptimizedDoubleBuffer, True)
        '  SetStyle(ControlStyles.SupportsTransparentBackColor, True)

        _imageControlList = New List(Of ImgControl)
        _animatorControlList = New List(Of CtlAnimator)
        Init()
    End Sub

    Private _imageControlList As IList(Of ImgControl)
    Private _animatorControlList As IList(Of CtlAnimator)

    Private _p As ProjectOutlineDataItem
    Private _bLoad As Boolean = False

    Public Property Loaded() As Boolean
        Get
            Return _bLoad
        End Get
        Set(ByVal value As Boolean)
            _bLoad = value
        End Set
    End Property

    Public ReadOnly Property PodItem() As ProjectOutlineDataItem
        Get
            Return _p
        End Get
    End Property

    Private Sub ProjectOutlineForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


        'Init()

        ''Log.log(tbccLogOperateType.View, "查看工程图")

        'AddHandler RTDReader.Instance.NewDataEvent, AddressOf OnNewData
        StartNewdataRefresh()


        'Dim modType As String
        'modType = readConfig("TransMode")
        'LEDDLL.SetTransMode(modType, 3)
        'LedView("", 1)
        'LedView("", 2)
        ''_bLoad = True
        ''RefreshControls()

        ''Me.Visible = False
        ''_bLoad = True
        ''  RefreshControls()
    End Sub


    Public Sub StartNewdataRefresh()
        _p = New ProjectOutlineDataItem(MainForm.MasterNetID)
        AddHandler _p.NewDataEvent, AddressOf NewData
        AddHandler _p.PlayAlarmSoundEvent, AddressOf NoticeAlarmSound
    End Sub

    'Private _page As TabPage

    'Private Function GetCurrentPage() As TabPage
    '    Return TabControlImages.SelectedTab
    'End Function

    ''' <summary>
    ''' 初始化
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Init()
        Dim pi As ProjectItem
        pi = MainForm.pi

        Dim psize As Size = Me.TabControlImages.Size
        Me.TabControlImages.TabPages.Clear()
        Me.TabControlImages.SuspendLayout()
        If pi Is Nothing Then
            Exit Sub
        End If
        For Each pii As ProjectImageItem In pi.imageList
            Dim page As New TabPage()
            page.Size = psize
            page.SuspendLayout()
            page.Text = pii.imageName
            'page.BackColor = Color.White

            '   Dim pic As New PictureBox


            'pic.BackColor = Color.Transparent

            'If System.IO.File.Exists(pii.imagePath) Then
            '    pic.Image = Image.FromFile(pii.imagePath)
            'End If
            If System.IO.File.Exists(pii.imagePath) Then
                '    pic.Image = Image.FromFile(pii.imagePath)
                ' pic.BackgroundImage = Image.FromFile(pii.imagePath)

            ElseIf System.IO.File.Exists(pii.imageoppPath) Then
                pii.imagePath = pii.imageoppPath
                '  pic.Image = Image.FromFile(pii.imagePath)
                '  pic.BackgroundImage = Image.FromFile(pii.imagePath)

            End If

            Dim lbl As New Label
            lbl.BackColor = Color.White
            lbl.Location = New Point(10, 10)
            lbl.ForeColor = Color.Red
            lbl.Font = New Font("宋体", 20)
            lbl.AutoSize = True
            lbl.Text = "提示:读取数据失败"
            lbl.Visible = False
            page.Controls.Add(lbl)


            LoadImgControls(pii, page)
            page.Tag = pii.imagePath
            page.BackgroundImageLayout = ImageLayout.None
            page.ResumeLayout()
            Me.TabControlImages.TabPages.Add(page)
            'pic.Dock = DockStyle.Fill
            'pic.SizeMode = PictureBoxSizeMode.StretchImage
            'page.Controls.Add(pic)
            ' page.BackgroundImageLayout = ImageLayout.Stretch
            'Dim bit As Bitmap = Bitmap.FromFile(pii.imageoppPath)
            'page.BackgroundImage = bit.GetThumbnailImage(page.Width, page.Height, Nothing, IntPtr.Zero)
            '  page.BackgroundImage = pic.Image





            '     pic.SendToBack()
        Next
        Me.TabControlImages.ResumeLayout()
    End Sub

    ''' <summary>
    ''' 加载控件
    ''' </summary>
    ''' <param name="pii"></param>
    ''' <param name="parentCtl"></param>
    ''' <remarks></remarks>
    Private Sub LoadImgControls(ByVal pii As ProjectImageItem, ByVal parentCtl As Control)
        For Each item As ImgControlItem In ImgControlService.GetControls(pii.projectID, pii.ImageID)
            Dim ctl As Control
            ctl = CreateImageControl(item, parentCtl)

            ''=========================
            '' lidalong
            '' 2010-09-21
            '' For: 支持库门状态
            If ctl IsNot Nothing Then
                If (TypeOf ctl Is CtlAnimator) Then
                    _animatorControlList.Add(ctl)
                Else
                    '' ImageContrl
                    _imageControlList.Add(ctl)
                End If

                parentCtl.Controls.Add(ctl)
                ctl.BringToFront()
            End If
        Next
    End Sub


    ''' <summary>
    ''' 创建图像控件
    ''' </summary>
    ''' <param name="item">要创建的图像控件</param>
    ''' <param name="parentCtl">父控件</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CreateImageControl(ByVal item As ImgControlItem, ByVal parentCtl As Control) As Control
        Dim ctl As Control
        '' ==========================
        '' lidalong
        '' 2010-09-21
        '' For: 支持库门状态
        If (item.IsDoorStatus) Then
            ctl = New CtlAnimator
            CType(ctl, CtlAnimator).ImgControlItem = item
            CType(ctl, CtlAnimator).IsDesign = False
            AddHandler CType(ctl, CtlAnimator).ShowDetailsEvent, AddressOf OnShowDetails
        Else
            ctl = New ImgControl(item.DataType)
            CType(ctl, ImgControl).ici = item
            CType(ctl, ImgControl).IsDesign = False
            AddHandler CType(ctl, ImgControl).ShowDetailsEvent, AddressOf OnShowDetails
        End If


        If ctl Is Nothing Then
            Return Nothing
        End If

        ' ctl.BackColor = Color.Blue
        Dim iWidth As Integer = parentCtl.Width
        Dim iHeight As Integer = parentCtl.Height

        ctl.Location = New Point((item.cLeft / 1024.0) * iWidth, (item.cTop / 768.0) * iHeight)
        'ctl.Size = New Size((item.cWidth / 1024.0) * iWidth, (item.cHeight / 768.0) * iHeight)
        ctl.Size = New Size(item.cWidth, item.cHeight)

        Return ctl
    End Function

    ''' <summary>
    ''' 双击显示对应明细数据
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub OnShowDetails(ByVal sender As Object, ByVal e As EventArgs)
        'Dim frm As Form = Nothing

        'Select Case sender.ctrlName
        '    Case "CompressorGroup"
        '        frm = New RTD_CompresserForm

        '    Case "Condenser"
        '        frm = New RTD_CondenserForm

        '    Case "Circuit"
        '        frm = New RTD_CircuitForm

        'End Select

        'If frm IsNot Nothing Then
        '    CType(frm, IRTDForm).SelectItem(sender.dataID)
        '    frm.ShowDialog()
        'End If

    End Sub

    ''' <summary>
    ''' 接收到实时数据
    ''' </summary>
    ''' <param name="sender">包含收到的数据</param>
    ''' <remarks></remarks>
    Private Sub NewData(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Try
            CType(sender, ProjectOutlineDataItem)._RefreshProcessing = True '正在刷新工程数据主窗口

            If e Is Nothing Then
                '读取数据失败
                'todo:提示读取数据失败
                SetReadErrorLableVisible(True)

                Logger.Write(User.Instance.uID, User.Instance.uName, String.Format("读取数据失败显示！"), tbccLogOperateType.Callback)


                'System.IO.File.AppendAllText("./ConnectInfo.Log", _
                '                            String.Format("{0} =====> 连接类型:{1}, {2}" & vbCrLf, Now, MainForm.pi.connectType, "提示读取数据失败"), _
                '                            System.Text.Encoding.UTF8)
            Else
                SetReadErrorLableVisible(False)

                '刷新所有控件值
                refreshControlval(sender)

                '刷新LED数据

                'Select Case MainForm.readConfig("SystemType")
                '    Case 0
                '        _refreshLedval(sender)
                '    Case Else
                'End Select
            End If

            CType(sender, ProjectOutlineDataItem)._RefreshProcessing = False  '刷新工程数据主窗口结束
        Catch ex As Exception
            Debug.Print("newdata exception\n")
            CType(sender, ProjectOutlineDataItem)._RefreshProcessing = False  '刷新工程数据主窗口结束
        End Try
    End Sub

    ''' <summary>
    ''' 通知报警或预警
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub NoticeAlarmSound(ByVal sender As Object, ByVal e As System.EventArgs)
        PlayAlarmSound()
    End Sub

    ''' <summary>
    ''' 播放报警声音
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub PlayAlarmSound()
        Dim fileName As String
        fileName = g_AlarmSoundFile
        If fileName = "" OrElse Not System.IO.File.Exists(fileName) Then
            Exit Sub
        End If
        ' My.Computer.Audio.Play(fileName, AudioPlayMode.Background)
        TBCC.Utility.Media.PlayerHelper.Instance().Play(fileName)
    End Sub


    Private Delegate Sub refreshControlvalhandler(ByVal sender As System.Object)

    ''' <summary>
    ''' 刷新界面控件
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub refreshControlval(ByVal sender As System.Object)
        If Me.InvokeRequired Then
            Dim d As New refreshControlvalhandler(AddressOf _refreshControlval)
            Me.Invoke(d, New Object() {sender})
        Else
            _refreshControlval(sender)
        End If
    End Sub

    ''' <summary>
    ''' 获取冷库类型
    ''' </summary>
    ''' <param name="refid"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetRefType(ByVal refid As Integer, ByVal netid As Integer, ByVal pID As String) As Integer
        Dim strSql As String
        strSql = "Select RefType From tbccrefinfo where projectID=?p0 and NetId=?p1 and RefId=?p2"
        Dim p(2) As MySql.Data.MySqlClient.MySqlParameter
        For i As Integer = 0 To p.Length - 1
            p(i) = New MySql.Data.MySqlClient.MySqlParameter()
        Next

        p(0).ParameterName = "p0" : p(0).Value = pID
        p(1).ParameterName = "p1" : p(1).Value = netid
        p(2).ParameterName = "p2" : p(2).Value = refid

        Dim obj As Object
        obj = SqlHelper.ExecuteScalar(strSql, p)

        If obj Is Nothing OrElse IsDBNull(obj) Then
            Return 0
        End If

        Return CInt(obj)

    End Function
    ''' <summary>
    ''' 刷新界面控件的值
    ''' </summary>
    ''' <remarks>
    ''' 对于声光，库门，断电进行状态的修改和颜色的变化
    ''' </remarks>
    Private Sub _refreshControlval(ByVal sender As System.Object)
        Dim v As ProjectOutlineDataItem
        Dim temp As Single
        v = CType(sender, ProjectOutlineDataItem)
        '刷新所有控件的值
        For Each item As ProjectOutlineDataItem.OutlineItem In v.outlineItemList '每个网络的数据
            'Debug.WriteLine("Item.netID=" & item.netID)
            For Each ctl As ImgControl In Me._imageControlList
                'Debug.WriteLine("ctl.netID=" & ctl.netID)
                If ctl.ici.Netid = item.netID Then
                    If ctl.ici.DataType = 1 OrElse ctl.ici.DataType = 2 Then '温度或湿度数据
                        temp = item.GetAiValue(ctl.ici.PortNo)
                        'If temp <> INVALID_DATA Then  '对于未激活冷库数据不进行显示



                        If Math.Abs(temp - INVALID_DATA) <= 0.001 Then '对于未激活冷库数据不进行显示
                            ctl.value = "##.#"
                            ctl.ForeColor = Color.Black
                            ctl.lblvalue.ForeColor = Color.Black
                        Else

                            ctl.value = Math.Round(item.GetAiValue(ctl.ici.PortNo), 1)





                            Select Case MainForm.readConfig("SystemType")
                                Case 0, 1

                                    Select Case (item.GetAiAlarmValue(ctl.ici.PortNo))
                                        Case 0  '无报警
                                            ctl.ForeColor = Color.Black
                                            ctl.lblvalue.ForeColor = Color.Black

                                        Case 1
                                            ctl.ForeColor = Color.Orange
                                            ctl.value = ctl.value + "↓"

                                            ctl.lblvalue.ForeColor = Color.Orange
                                        Case 2
                                            ctl.ForeColor = Color.Orange
                                            ctl.value = ctl.value + "↑"
                                            ctl.lblvalue.ForeColor = Color.Orange

                                        Case 3
                                            ctl.ForeColor = Color.Red
                                            ctl.value = ctl.value + "↓"
                                            ctl.lblvalue.ForeColor = Color.Red

                                        Case 4
                                            ctl.ForeColor = Color.Red
                                            ctl.value = ctl.value + "↑"
                                            ctl.lblvalue.ForeColor = Color.Red


                                        Case Else
                                            ctl.ForeColor = Color.Black
                                            ctl.lblvalue.ForeColor = Color.Black

                                    End Select

                                Case 2  '类型为2修改所有数据为合格数据
                                    Select Case MainForm.readConfig("Type")
                                        Case 1

                                            Select Case (item.GetAiAlarmValue(ctl.ici.PortNo))
                                                Case 0  '无报警
                                                    ctl.ForeColor = Color.Black
                                                    ctl.lblvalue.ForeColor = Color.Black

                                                Case 1
                                                    ctl.ForeColor = Color.Orange
                                                    ctl.value = ctl.value + "↓"

                                                    ctl.lblvalue.ForeColor = Color.Orange
                                                Case 2
                                                    ctl.ForeColor = Color.Orange
                                                    ctl.value = ctl.value + "↑"
                                                    ctl.lblvalue.ForeColor = Color.Orange

                                                Case 3
                                                    ctl.ForeColor = Color.Red
                                                    ctl.value = ctl.value + "↓"
                                                    ctl.lblvalue.ForeColor = Color.Red

                                                Case 4
                                                    ctl.ForeColor = Color.Red
                                                    ctl.value = ctl.value + "↑"
                                                    ctl.lblvalue.ForeColor = Color.Red


                                                Case Else
                                                    ctl.ForeColor = Color.Black
                                                    ctl.lblvalue.ForeColor = Color.Black

                                            End Select

                                        Case 0

                                            '修改湿度数据为合格数据
                                            If ctl.ici.DataType = 2 Then

                                                If ctl.value = "##.#" Then

                                                Else

                                                    If ctl.value > g_HumType1max Then

                                                        If ctl.value.LastIndexOf(".") >= 0 Then
                                                            ctl.value = g_HumType1max - 1 + ctl.value.Remove(0, ctl.value.LastIndexOf(".")) '+数据小数点儿'+数据小数点儿
                                                        Else
                                                            ctl.value = g_HumType1max

                                                        End If

                                                    ElseIf ctl.value < g_HumType1min Then
                                                        If ctl.value.LastIndexOf(".") >= 0 Then
                                                            ctl.value = g_HumType1min + ctl.value.Remove(0, ctl.value.LastIndexOf(".")) '+数据小数点儿'+数据小数点儿

                                                        Else
                                                            ctl.value = g_HumType1min

                                                        End If


                                                    End If

                                                End If


                                            End If


                                            If ctl.ici.DataType = 1 Then
                                                If ctl.value = "##.#" Then
                                                Else
                                                    Select Case GetRefType(ctl.ici.Refid, ctl.ici.Netid, ctl.ici.ProjectID)
                                                        Case 1   '冷库
                                                            If ctl.value > g_TemType1max Then
                                                                If ctl.value.LastIndexOf(".") >= 0 Then
                                                                    ctl.value = g_TemType1max - 1 + ctl.value.Remove(0, ctl.value.LastIndexOf(".")) '+数据小数点儿

                                                                Else
                                                                    ctl.value = g_TemType1max

                                                                End If


                                                            ElseIf ctl.value < g_TemType1min Then

                                                                If ctl.value.LastIndexOf(".") >= 0 Then
                                                                    ctl.value = g_TemType1min + ctl.value.Remove(0, ctl.value.LastIndexOf(".")) '+数据小数点儿
                                                                Else
                                                                    ctl.value = g_TemType1min

                                                                End If

                                                            End If
                                                        Case 2  '阴凉库
                                                            If ctl.value > g_TemType2max Then

                                                                If ctl.value.LastIndexOf(".") >= 0 Then
                                                                    ctl.value = g_TemType2max - 1 + ctl.value.Remove(0, ctl.value.LastIndexOf(".")) '+数据小数点儿
                                                                Else
                                                                    ctl.value = g_TemType2max

                                                                End If

                                                            ElseIf ctl.value < g_TemType2min Then
                                                                If ctl.value.LastIndexOf(".") >= 0 Then
                                                                    ctl.value = g_TemType2min + ctl.value.Remove(0, ctl.value.LastIndexOf(".")) '+数据小数点儿
                                                                Else
                                                                    ctl.value = g_TemType2min

                                                                End If

                                                            End If
                                                        Case 3  '冰库
                                                            If ctl.value > g_TemType3max Then
                                                                If ctl.value.LastIndexOf(".") >= 0 Then
                                                                    ctl.value = g_TemType3max - 1 + ctl.value.Remove(0, ctl.value.LastIndexOf(".")) '+数据小数点儿
                                                                Else
                                                                    ctl.value = g_TemType3max

                                                                End If


                                                            ElseIf ctl.value < g_TemType3min Then
                                                                If ctl.value.LastIndexOf(".") >= 0 Then
                                                                    ctl.value = g_TemType3min + ctl.value.Remove(0, ctl.value.LastIndexOf(".")) '+数据小数点儿
                                                                Else
                                                                    ctl.value = g_TemType3min

                                                                End If
                                                            End If
                                                        Case 4  '低温库
                                                            If ctl.value > g_TemType4max Then
                                                                If ctl.value.LastIndexOf(".") >= 0 Then
                                                                    ctl.value = g_TemType4max - 1 + ctl.value.Remove(0, ctl.value.LastIndexOf("."))

                                                                Else
                                                                    ctl.value = g_TemType4max

                                                                End If

                                                            ElseIf ctl.value < g_TemType4min Then
                                                                If ctl.value.LastIndexOf(".") >= 0 Then
                                                                    ctl.value = g_TemType4min + ctl.value.Remove(0, ctl.value.LastIndexOf("."))
                                                                Else
                                                                    ctl.value = g_TemType4min

                                                                End If
                                                            End If
                                                        Case Else


                                                    End Select

                                                End If

                                            End If


                                        Case Else



                                    End Select



                                Case Else


                            End Select


                        End If


                    ElseIf ctl.ici.DataType = 3 Then '报警数据
                        '#If LSC_WMS_SWITCH = "PREALARM" Then
                        '' ==========================================
                        '' cause:   修改为库门报警、声光和断电 为预警
                        '' author:  李大龙
                        '' date:    2009-11-10
                        '' see:     3.4.3.1 R1.001
                        '' =========================================
                        If ctl.ici.PortNo = 1 Then '冷库报警  （此处使用报警数据中不用的portno表示不同的报警类型）
                            ctl.value = item.GetRefAlarmStatus(ctl.ici.Refid, ctl.ici.Netid)
                        ElseIf ctl.ici.PortNo = 2 Then '声光报警功能

                            ctl.value = item.GetSoundAlarmStatus(ctl.ici.Refid, ctl.ici.Netid)

                        ElseIf ctl.ici.PortNo = 3 Then '缺项报警功能
                            ctl.value = item.GetLostPowerStatus_LSC_WMS(ctl.ici.Refid, ctl.ici.Netid)
                            ''==================================
                            '' Cause: 增加库门状态显示
                            '' author: 李大龙
                            '' data: 2011-1-6
                            '' See: None
                        ElseIf ctl.ici.PortNo = 4 And ctl.ImgControlType = 3 Then '库门报警功能
                            ctl.value = item.GetDoorAlarmStatus_LSC_WMS(ctl.ici.Refid)
                        ElseIf ctl.ici.PortNo = 4 And ctl.ImgControlType = 5 Then '库门状态
                            ctl.value = item.GetDoorAlarmStatus_LSC_WMS(ctl.ici.Refid)
                            ctl.value = item.GetDoorStatus_LSC_WMS(ctl.ici.Refid)

                        ElseIf ctl.ici.PortNo = 5 And ctl.ImgControlType = 3 Then '库门2报警功能
                            ctl.value = item.GetDoor2AlarmStatus_LSC_WMS(ctl.ici.Refid)
                        ElseIf ctl.ici.PortNo = 5 And ctl.ImgControlType = 5 Then '库门2状态
                            ctl.value = item.GetDoor2Status_LSC_WMS(ctl.ici.Refid)
                        ElseIf ctl.ici.PortNo = 6 Then '冷库联动状态
                            ctl.value = item.GetJointActionOpen_Output_Status(ctl.ici.Refid, ctl.ici.Netid)
                        ElseIf ctl.ici.PortNo = 7 Then '冷库联动状态
                            ctl.value = item.GetJointActionClose_Output_Status(ctl.ici.Refid, ctl.ici.Netid)
                        ElseIf ctl.ici.PortNo = 8 Then '冷库联动状态
                            ctl.value = item.GetJointAction_Output_Status(ctl.ici.Refid, ctl.ici.Netid)
                        ElseIf ctl.ici.PortNo = 9 Then '除霜状态输入

                            If ctl.ImgControlType = 6 Then  '除霜预警
                                ctl.value = item.GetDefrostTempStatus(ctl.ici.Refid)
                            Else
                                ctl.value = item.GetDefrostStatus_Input_Status(ctl.ici.Refid, ctl.ici.Netid)
                            End If

                            ' ElseIf ctl.ici.PortNo = 9 And ctl.ImgControlType = 6 Then

                        ElseIf ctl.ici.PortNo = 10 Then '发电机预警
                            ctl.value = item.GeneratorStatus()
                        ElseIf ctl.ici.PortNo = 11 Then '制冷状态输入端口
                            ctl.value = item.GetCoolingStatus(ctl.ici.Refid)
                        ElseIf ctl.ici.PortNo = 12 Then '发电机预警
                            ctl.value = item.GetCompressorSetFailureStatus(ctl.ici.Refid)
                        ElseIf ctl.ici.PortNo = 13 Then '发电机预警
                            ctl.value = item.GetCompressorFailureStatus(ctl.ici.Refid)
                        ElseIf ctl.ici.PortNo = 15 Then '除霜温度
                            ' ctl.value = item.GetDefrostTempStatus(ctl.ici.Refid)
                            Dim defrostportno As Integer
                            defrostportno = getdefrostportno(ctl.ici.Refid, ctl.ici.Netid, ctl.ici.ProjectID)


                            '获取除霜端口
                            ctl.value = Math.Round(item.GetAiValue(defrostportno), 1)

                        ElseIf ctl.ici.PortNo = 14 Then '压缩机运行状态
                            ctl.value = item.Compressor_Input_Status(ctl.ici.Refid)

                        End If
                        '#Else

                        '                        If ctl.ici.PortNo = 1 Then '冷库报警  （此处使用报警数据中不用的portno表示不同的报警类型）
                        '                            ctl.value = item.GetRefAlarmStatus(ctl.ici.Refid)
                        '                        ElseIf ctl.ici.PortNo = 2 Then '声光报警功能

                        '                            ctl.value = item.GetSoundAlarmStatus(ctl.ici.Refid)

                        '                        ElseIf ctl.ici.PortNo = 3 Then '缺项报警功能
                        '                            ctl.value = item.GetLostPowerStatus(ctl.ici.Refid)

                        '                        ElseIf ctl.ici.PortNo = 4 Then '库门报警功能
                        '                            ctl.value = item.GetDoorAlarmStatus(ctl.ici.Refid)
                        '                        End If
                        '#End If

                    End If
                End If
            Next


            '实时数据库门控件解析
            For Each CtlA As CtlAnimator In Me._animatorControlList

                If CtlA.ImgControlItem.Netid = item.netID Then

                    If CtlA.ImgControlItem.DataType = 4 Then

                        If CtlA.ImgControlItem.PortNo = 4 Then
                            If item.GetDoorStatus_LSC_WMS(CtlA.ImgControlItem.Refid) = "开启" Then
                                CtlA.Open()


                            ElseIf item.GetDoorStatus_LSC_WMS(CtlA.ImgControlItem.Refid) = "关闭" Then
                                CtlA.Close()

                            End If
                        End If

                        If CtlA.ImgControlItem.PortNo = 5 Then

                            If item.GetDoor2Status_LSC_WMS(CtlA.ImgControlItem.Refid) = "开启" Then
                                CtlA.Open()


                            ElseIf item.GetDoor2Status_LSC_WMS(CtlA.ImgControlItem.Refid) = "关闭" Then
                                CtlA.Close()

                            End If

                        End If



                    End If

                End If

            Next

        Next
    End Sub
    Public Function getdefrostportno(ByVal refid As Integer, ByVal netid As Integer, ByVal proID As String) As Integer

        ' Dim portid As Integer

        Dim strSql As String
        strSql = "Select DefrostTemp_Input_Nu from tbccdidoinfo where projectID=?p0 and Netid=?p1  and RefId=?p2"

        Dim p(2) As MySql.Data.MySqlClient.MySqlParameter
        p(0) = New MySql.Data.MySqlClient.MySqlParameter
        p(0).ParameterName = "p0" : p(0).Value = proID

        p(1) = New MySql.Data.MySqlClient.MySqlParameter
        p(1).ParameterName = "p1" : p(1).Value = netid

        p(2) = New MySql.Data.MySqlClient.MySqlParameter
        p(2).ParameterName = "p2" : p(1).Value = refid

        Dim obj As Object
        obj = SqlHelper.ExecuteScalar(strSql, p)

        If obj Is Nothing OrElse IsDBNull(obj) Then
            Return 0
        Else
            Return CInt(obj)
        End If

        '  Return portid

    End Function

    Private Delegate Sub SetReadErrorLableVisibleHandler(ByVal bVisible As Boolean)
    Private Delegate Sub refreshLedvalhandler(ByVal sender As System.Object)

    ''' <summary>
    ''' 设置“读取数据失败”标签是否可见
    ''' </summary>
    ''' <param name="bVisible"></param>
    ''' <remarks></remarks>
    Private Sub SetReadErrorLableVisible(ByVal bVisible As Boolean)
        If Me.InvokeRequired Then
            Try
                Dim d As New SetReadErrorLableVisibleHandler(AddressOf _setReadErrorLableVisible)
                Me.Invoke(d, New Object() {bVisible})
            Catch ex As Exception
                Debug.WriteLine(ex.ToString())
            End Try

        Else
            _setReadErrorLableVisible(bVisible)
        End If
    End Sub
    Private finished As Boolean = False
    Private LedList As New ArrayList
    Private index As Integer = 0
    Private SUMLEDvalue As Integer = readConfig("Allref")

    Private Sub LedView(ByVal str As String, ByVal netid As Integer)

        LEDDLL.SetSerialPortPara(netid, readConfig("port"), readConfig("rate"))
        ' LEDDLL.SetSerialPortPara(netid, 3, 115200)
        ' LEDDLL.SendScreenPara(netid, 1, 192, 48)
        LEDDLL.StartSend()
        LEDDLL.AddControl(netid, 1)
        LEDDLL.AddProgram(netid, 1, 1)
        LEDDLL.AddFileArea(netid, 1, 1, 0, 0, 192, 48)
        LEDDLL.AddFileString(netid, 1, 1, 1, str, "宋体", 12, 255, False, False, False, 1, 192, 48, 1, 255, 10, 1, 1)
        ' LEDDLL.AddFileString(netid, 1, 1, 1, str, "宋体", 12, 255, False, False, False, 192, 48, 1, 255, 10, 1, 1)
        '' 'LEDDLL.AddQuitText(netid, 1, 1, 0, 0, 64, 12, 255, "宋体", 12, 0, False, False, "1")
        LEDDLL.SendControl(netid, 1, IntPtr.Zero)

    End Sub
    Private Sub LedView1(ByVal str As String, ByVal netid As Integer)

        LEDDLL.SetSerialPortPara(netid, readConfig("port"), readConfig("rate"))

        LEDDLL.StartSend()
        LEDDLL.AddControl(netid, 1)
        LEDDLL.AddProgram(netid, 1, 1)
        LEDDLL.AddFileArea(netid, 1, 1, 0, 0, 192, 48)
        LEDDLL.AddFileString(netid, 1, 1, 1, str, "宋体", 12, 255, False, False, False, 1, 192, 48, 1, 255, 10, 1, 1)
        LEDDLL.SendControl(netid, 1, IntPtr.Zero)

    End Sub
    Private Function readConfig(ByVal strkey As String) As String

        Dim strreturn As String
        Dim appreader As Configuration.AppSettingsReader = New Configuration.AppSettingsReader()
        Try
            strreturn = appreader.GetValue(strkey, Type.GetType("System.String")).ToString()
        Catch ex As Exception
            strreturn = ex.Message.ToString()
        Finally
            appreader = Nothing
        End Try
        Return strreturn
    End Function
    '''' <summary>
    '''' 刷新LED控件
    '''' </summary>
    '''' <remarks></remarks>
    'Private Sub refreshLedval(ByVal sender As System.Object)
    '    If Me.InvokeRequired Then
    '        Dim d As New refreshLedvalhandler(AddressOf _refreshLedval)
    '        Me.Invoke(d, New Object() {sender})
    '    Else
    '        _refreshLedval(sender)
    '    End If
    'End Sub
    ''' <summary>
    ''' 刷新LED数据
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <remarks></remarks>
    Private Sub _refreshLedval(ByVal sender As System.Object)


        Dim rts As RefTypeService = New RefTypeService(MainForm.pi)

        Dim avgTemp As String = Nothing
        Dim avgHi As String = Nothing
        Dim tempval As New ArrayList
        Dim hival As New ArrayList
        Dim sumtemp As Single = 0
        Dim sumhi As Single = 0
        Dim num As Single
        Dim temp As Single

        Dim v As ProjectOutlineDataItem
        v = CType(sender, ProjectOutlineDataItem)

        '刷新所有控件的值
        For Each item As ProjectOutlineDataItem.OutlineItem In v.outlineItemList '每个网络的数据

            For Each rti As RefTypeItem In rts.GeRefGroupList(item.netID)
                Dim aiport As AiPortTypeService = New AiPortTypeService(rti)

                Dim RefVal As New LedViewVal

                For Each ai As AiPortTypeItem In aiport.GetAiList(rti.RefId)

                    Dim ledvalue As New LEDdata

                    If ai.DataType = 1 Then
                        num = item.GetAiValue(ai.PortNo)
                        If Math.Abs(num - INVALID_DATA) <= 0.001 Then

                            ledvalue.portdata = "---"

                            ledvalue.portname = ai.PortName

                            
                        Else

                            RefVal.Tempname = ai.PortName

                            ledvalue.portname = ai.PortName
                            ledvalue.portdata = Math.Round(item.GetAiValue(ai.PortNo), 1).ToString + "℃"

                            ' tempval.Add(item.GetAiValue(ai.PortNo))


                        End If
                    Else
                        temp = item.GetAiValue(ai.PortNo)
                        If Math.Abs(num - INVALID_DATA) <= 0.001 Then

                            ledvalue.portname = ai.PortName

                            ledvalue.portdata = "---"
                        Else

                            RefVal.Humname = ai.PortName
                            'hival.Add(item.GetAiValue(ai.PortNo))
                            ledvalue.portname = ai.PortName
                            ledvalue.portdata = Math.Round(item.GetAiValue(ai.PortNo), 1).ToString + "%"



                        End If

                    End If

                    RefVal.LedList.Add(ledvalue)

                Next
                'For j As Integer = 0 To tempval.Count - 1
                '    sumtemp = sumtemp + tempval.Item(j)
                '    tempval.Remove(j)
                'Next
                'If tempval.Count <> 0 Then
                '    avgTemp = CStr(Math.Round((sumtemp / tempval.Count), 2))
                'Else

                '    avgTemp = INVALID_DATA
                'End If

                'For k As Integer = 0 To hival.Count - 1
                '    sumhi = sumhi + hival.Item(k)
                '    hival.Remove(k)
                'Next
                'If hival.Count <> 0 Then
                '    avgHi = CStr(Math.Round((sumhi / hival.Count), 2))
                'Else
                '    avgHi = INVALID_DATA

                'End If

                RefVal.netid = item.netID
                RefVal.refid = rti.RefId
                RefVal.refname = rti.RefName

                If KeyValuePairClass.GetValue(MainForm.pi.ProjectID, (item.netID.ToString("000") + rti.RefId.ToString)) Is String.Empty Then
                    RefVal.LedNo = 0
                Else
                    RefVal.LedNo = KeyValuePairClass.GetValue(MainForm.pi.ProjectID, (item.netID.ToString("000") + rti.RefId.ToString)).Substring(3)
                End If


                'If avgTemp = INVALID_DATA Then
                '    RefVal.avgTemp = "----"

                'Else
                '    RefVal.avgTemp = avgTemp + "℃"

                'End If

                'If avgHi = INVALID_DATA OrElse avgHi = 0 Then
                '    RefVal.avgHi = "----"

                'Else
                '    RefVal.avgHi = avgHi + "%"

                'End If
                ' RefVal.avgHi = ""

                RefVal.alarmState = item.GetRefAlarmStatus(rti.RefId, item.netID)

                'If item.GetLostPowerStatus_LSC_WMS(rti.RefId, item.netID) = "正常" Then
                'Else

                '    RefVal.alarmState = RefVal.alarmState + "  " + "断电预警"


                'End If



                LedValueList.Add(RefVal)



                tempval.Clear()
                hival.Clear()
                sumtemp = 0
                sumhi = 0
                avgTemp = 0
                avgHi = 0




                '处理冷库与LED配置关系

                If RefVal.LedNo <> 0 Then '冷库配置了LED号码，显示LED


                    Dim b As Boolean = False
                    Dim no As Integer = 0
                    Dim LedSumNo As Integer = GetLEDSumNo(MainForm.pi.ProjectID, ("LED" + RefVal.LedNo.ToString)) ' 该LED中显示冷库的数量

                    If RefLedList.Count <> 0 Then

                        For Each i As LedViewVal In RefLedList    '判断是否所有

                            If i.LedNo = RefVal.LedNo Then
                                no += 1
                            End If

                        Next

                        If LedSumNo = no Then  '清空所有之前显示过的该LED数据
                            For j As Integer = 0 To RefLedList.Count - 1
                                If j = RefLedList.Count Then
                                    Exit For
                                End If
                                Dim k As LedViewVal = RefLedList(j)
                                If k.LedNo = RefVal.LedNo Then
                                    RefLedList.Remove(k)
                                    j -= 1
                                End If
                            Next


                            LedListview(RefVal, RefVal.LedNo)  '添加LED显示到屏幕

                            RefLedList.Add(RefVal)  '记录该冷库屏幕已显示数据

                            Lednolist.Add(RefVal.LedNo)

                        Else '数据中之前有显示冷库数据


                            For Each refitem As LedViewVal In RefLedList
                                If RefVal.netid = refitem.netid AndAlso RefVal.refid = refitem.refid Then
                                    b = True
                                    Exit For

                                End If

                            Next


                            If b Then
                                b = False
                                Continue For

                            End If



                            If Lednolist.Contains(RefVal.LedNo) Then
                                Continue For

                            End If

                            LedListview(RefVal, RefVal.LedNo)  '添加LED显示到屏幕

                            RefLedList.Add(RefVal)  '记录该冷库屏幕已显示数据

                            Lednolist.Add(RefVal.LedNo)

                        End If

                        no = 0




                    Else

                        LedListview(RefVal, RefVal.LedNo)  '添加LED显示到屏幕

                        RefLedList.Add(RefVal)  '记录该冷库屏幕已显示数据

                        Lednolist.Add(RefVal.LedNo)


                    End If



                End If






            Next
        Next

        Lednolist.Clear()



        '显示所有冷库LED数据

        If SUMLEDvalue <> 0 Then

            Dim a As Boolean = False



            For Each item As LedViewVal In LedValueList
                If LedShowList.Count = LedValueList.Count Then



                    LedShowList.Clear()

                    LedListview(item, SUMLEDvalue)
                    LedShowList.Add(item)


                    Exit For
                Else

                    For Each Leditem As LedViewVal In LedShowList
                        If item.netid = Leditem.netid AndAlso item.refid = Leditem.refid Then
                            a = True
                            Exit For

                        End If
                    Next



                    If a Then
                        a = False
                        Continue For
                    Else


                        LedListview(item, SUMLEDvalue)

                        LedShowList.Add(item)
                        'a = False
                        Exit For
                    End If

                End If

            Next




        End If


        LedValueList.Clear()



    End Sub
    Private Function GetLEDSumNo(ByVal pid As String, ByVal no As String) As Integer

        Dim strSql As String
        strSql = "Select count(*) From tbccDictory where projectID=?p0 and `value`=?p1"
        Dim p(1) As MySql.Data.MySqlClient.MySqlParameter
        For i As Integer = 0 To p.Length - 1
            p(i) = New MySql.Data.MySqlClient.MySqlParameter()
        Next

        p(0).ParameterName = "p0" : p(0).Value = pid
        p(1).ParameterName = "p1" : p(1).Value = no

        Dim obj As Object
        obj = SqlHelper.ExecuteScalar(strSql, p)

        Return CInt(obj)

    End Function
    Private Function LedListview(ByVal Ledlist As LedViewVal, ByVal netid As Integer) As Boolean
        Dim str As String
        Dim str1 As String = ""
        Dim str2 As String = ""
        Dim space As String = " "
        Dim LEDdatashow As New List(Of LEDdata)

        str = Ledlist.refname + ":" + space + Ledlist.alarmState
        Do Until str.Length = 24

            If str.Length > 24 Then
                str.Remove(str.Length - 1, 1)
            ElseIf str.Length < 24 Then
                str += space

            End If

        Loop


        For n As Integer = 0 To Ledlist.LedList.Count - 1

            'str = Ledlist.refname + ":" + space + Ledlist.alarmState
            'Do Until str.Length = 24

            '    If str.Length > 24 Then
            '        str.Remove(str.Length - 1, 1)
            '    ElseIf str.Length < 24 Then
            '        str += space

            '    End If

            'Loop
            Dim item As New LEDdata
            item = Ledlist.LedList.Item(n)

            If n Mod 2 = 0 Then
                str1 = item.portname + ":" + space + item.portdata
                Do Until str1.Length = 24
                    str1 += space
                Loop

            Else
                str2 = item.portname + ":" + space + item.portdata
                Do Until str2.Length = 24
                    str2 += space
                Loop

            End If

            If n Mod 2 = 0 Then
                If n = Ledlist.LedList.Count - 1 Then
                    LedView(str + str1, netid)
                    'str = ""

                End If
            Else
                LedView(str + str1 + str2, netid)
                ' str = ""
                System.Threading.Thread.Sleep(1500)

            End If

            ' system.Threading.slee




        Next

        'For Each item As LEDdata In Ledlist.LedList

        '    If LEDdatashow.Count = Ledlist.LedList.Count Then
        '        LEDdatashow.Clear()
        '        Return True
        '    Else

        '        If LEDdatashow.Contains(item) Then
        '            Continue For
        '        Else




        '            LEDdatashow.Add(item)

        '        End If



        '    End If

        'Next


        'If Ledlist.avgTemp <> "----" Then
        '    str = str + "平均温度:" + space + Ledlist.avgTemp '+ space + space + space + "平均湿度" + space + space


        '    'str1 = space + space + Ledlist.avgTemp
        '    Do Until str.Length = 48
        '        str += space
        '    Loop

        'End If



        'If Ledlist.avgHi <> "----" Then
        '    str = str + "平均湿度:" + space + Ledlist.avgHi

        '    Do Until str.Length = 72
        '        str += space
        '    Loop

        'End If







        '  LedView(str, netid)
        Return True
    End Function
    Private LedValueList As New List(Of LedViewVal)
    Private LedShowList As New List(Of LedViewVal)
    Private RefLedList As New List(Of LedViewVal)
    Private Lednolist As New ArrayList
    Private Class LedViewVal
        Public netid As Integer
        Public refid As Integer
        Public LedNo As Integer
        Public LedType As Integer
        Public refname As String
        Public Tempname As String
        Public Humname As String
        Public avgTemp As String
        Public avgHi As String
        Public alarmState As String
        Public LedList As New List(Of LEDdata)
    End Class
    Private Class LEDdata
        Public portname As String
        Public portdata As String

    End Class

    ''' <summary>
    ''' 设置“读取数据失败”标签是否可见
    ''' </summary>
    ''' <param name="bVisible"></param>
    ''' <remarks></remarks>
    Private Sub _setReadErrorLableVisible(ByVal bVisible As Boolean)
        For Each page As TabPage In Me.TabControlImages.TabPages
            For Each ctl As Control In page.Controls
                If ctl.GetType().ToString() = GetType(Label).ToString() Then
                    ctl.Visible = bVisible
                End If
            Next
        Next
    End Sub


    ''' <summary>
    ''' 刷新工程数据显示控件的位置
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub RefreshControls()
        If _bLoad Then
            For Each page As TabPage In Me.TabControlImages.TabPages
                page.BackgroundImage = Nothing
                page.SuspendLayout()
                Dim iWidth As Integer = page.Width
                Dim iHeight As Integer = page.Height

                For Each ctl As Control In page.Controls
                    If ctl.GetType IsNot GetType(PictureBox) AndAlso ctl.GetType IsNot GetType(Label) Then

                        '' ====================================
                        '' lidalong
                        '' 2010-09-21
                        '' for:支持库门状态
                        If (TypeOf ctl Is CtlAnimator) Then
                            Dim item As ImgControlItem = CType(ctl, CtlAnimator).ImgControlItem
                            '( X / 1024.0) * iWidth为相对位置（百分比位置）
                            ctl.Location = New Point((item.cLeft / 1024.0) * iWidth, (item.cTop / 768.0) * iHeight)
                            'ctl.Size = New Size((item.cWidth / 1024.0) * iWidth, (item.cHeight / 768.0) * iHeight)
                            'ctl.Size = New Size(item.cWidth, item.cHeight)

                        ElseIf (TypeOf ctl Is ImgControl) Then

                            Dim item As ImgControlItem = CType(ctl, ImgControl).ici
                            '( X / 1024.0) * iWidth为相对位置（百分比位置）
                            ctl.Location = New Point((item.cLeft / 1024.0) * iWidth, (item.cTop / 768.0) * iHeight)
                            'ctl.Size = New Size((item.cWidth / 1024.0) * iWidth, (item.cHeight / 768.0) * iHeight)
                            'ctl.Size = New Size(item.cWidth, item.cHeight)
                        End If


                    End If
                Next
                Try
                    Dim bit As Bitmap = Bitmap.FromFile(page.Tag.ToString())
                    page.BackgroundImage = bit.GetThumbnailImage(page.Width, page.Height, Nothing, IntPtr.Zero)
                Catch ex As Exception
                    page.BackgroundImage = Nothing
                End Try

                page.ResumeLayout()
            Next
        End If
    End Sub




    Private Sub TabControlImages_SizeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControlImages.SizeChanged
        '刷新工程数据显示控件的位置
        If (Me.Loaded) Then
            RefreshControls()
        End If

    End Sub

    Private Sub TabControlImages_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControlImages.SelectedIndexChanged
        '刷新工程数据显示控件的位置
        If (Me.Loaded) Then
            RefreshControls()
        End If

    End Sub



    ''' <summary>
    ''' 窗体关闭时,停止数据的刷新
    ''' </summary>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)
        If _p IsNot Nothing Then
            _p.StopDataTransfer()
        End If

        MyBase.OnClosing(e)
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Timer1.Stop()
        Timer1.Enabled = False
        RefreshControls()
    End Sub
End Class